//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
declare function onStageSize(_size:any,_obj:any);
declare function InitServerUrl(str:string);
declare var Cookies;
class Main extends eui.UILayer{
    /*
    JS 调用
    */
    //是否横屏 ， 是否旋转
    private crossScreenCount:number = 0;
    public transverse(isCrossScreen,isRotation){
        //alert("收到:"+isCrossScreen+" : "+isRotation);
         this.crossScreenCount = 0;
            if(egret.localStorage.getItem("isCrossScreenClew")){
                this.crossScreenCount = Number(egret.localStorage.getItem("isCrossScreenClew"));
            }
        if(isCrossScreen&&this.crossScreenCount<3){//允许提示三次
            // 显示提示            
            this.openRotationClew();
        }else{
            // 隐藏提示
            this.closeRotationClew();
        }
    }
    //this , w , h , 分辨率，机型   
    private sizeTimer;
    public onSize(thisRef:any,w:number,h:number,radio:number,phone:string){  
        var endW:number=0;
        var endH:number=0;
        endW=1166;
        endH=720;
        thisRef.stage.setContentSize(endW,endH);
        /*thisRef.stage.orientation = egret.OrientationMode.AUTO;
                var endW:number=0;
                var endH:number=0;
                if(phone=="ios"){
                    endW=w*radio;
                    endH=h*radio;
                }else if(phone=="pc"){
                    endW=w;
                    endH=h;
                }else if(phone=="android"){
                    endW = 1166;//document.documentElement.clientHeight*radio;
                    endH = 720;//document.documentElement.clientWidth*radio;
                }else{
                endW=w*radio;
                endH=h*radio;
                }
                if(endW%2!=0) endW+=1;
                if(endH%2!=0) endH+=1;
                if(phone=="pc"||phone=="ios"){
                thisRef.stage.setContentSize(endW,endH);
                if(phone=="pc"){
                    endW=1166;
                    endH=720;
                    thisRef.stage.setContentSize(endW,endH);
                    thisRef.stage.orientation = egret.OrientationMode.AUTO;
                }else thisRef.stage.orientation = egret.OrientationMode.LANDSCAPE_FLIPPED;
                //thisRef.stageSize(null);
                }*/
        StageData.W = endW;
        StageData.H = endH; 
        StageData.MainObj.dispatchEventWith(Events.STAGE_SIZE);              
    }
    private rotationImage:egret.Bitmap;
    private openRotationClew(){
        this.closeRotationClew();
        this.rotationImage = MyLibrary.createBitmapByName("rotationClew_png");
        this.rotationImage.touchEnabled = true;
        this.addChild(this.rotationImage);
        this.rotationImage.addEventListener(egret.TouchEvent.TOUCH_TAP,this.returnRotationClew,this);
    }
    private returnRotationClew(){
        this.crossScreenCount ++;
        egret.localStorage.setItem("isCrossScreenClew",String(this.crossScreenCount));
        this.closeRotationClew();
    }
    private closeRotationClew(){
        if(this.rotationImage){
            this.rotationImage.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.closeRotationClew,this);
            this.removeChild(this.rotationImage);
            this.rotationImage = null;
        }
    }
    
    /**
     * 加载进度界面
     * loading process interface
     */
    public isWeiXin():boolean
    {
        var ua:string = navigator.userAgent.toString();

        var str:any=ua.match(/MicroMessenger/i);
        if(str=="MicroMessenger") {
             return true;
         } else {
             return false;
         }
    }
    
    // private initTxt:egret.TextField;
    private loadingView: LoadingUI;
    protected createChildren(): void {
        super.createChildren();         
        // if(!this.isWeiXin()){
        //     alert("请在微信中打开...");
        //     return;
        // }         
        this.name = "_main";
        StageData.MainObj = this;
        StageData.W = this.stage.stageWidth;
        StageData.H = this.stage.stageHeight;
        

        //添加声音
        StageData.soundObj = new soundPlay();
        this.addChild(StageData.soundObj);
        
        // this.initTxt = new egret.TextField();
        // this.initTxt.fontFamily = "微软雅黑";
        // this.initTxt.bold = true;
        // this.initTxt.textColor = 0x496F99;
        // this.initTxt.text = "请稍等..."; 
        // this.initTxt.y = StageData.H/2;
        // this.initTxt.x = (StageData.W-this.initTxt.textWidth)/2;
        // this.addChild(this.initTxt);

        //设置加载进度界面
        this.loadingView = new LoadingUI();
        this.addChild(this.loadingView);
        this.loadingView.beforeCreateView()

        //获取浏览器缓存 （获取声音设置）
        try{    
            var lsString:string = egret.localStorage.getItem("soundClose");
            var lsString2:string = egret.localStorage.getItem("bgMusicClose");
            var ignore:string = egret.localStorage.getItem("ignore");

            //alert(GameData.ignore);
            if(ignore){     
                GameData.ignore = ignore; 
            }else{
                var timestamp1 = Date.parse(new Date().toString()); 
                    timestamp1 = timestamp1/1000;
                    GameData.ignore = String(timestamp1);  
                    egret.localStorage.setItem("ignore",GameData.ignore);
            }
            
            if(lsString == "true"){
                StageData.soundClose = true;
            }else if(lsString == "false"){
                StageData.soundClose = false;
            }            

            if(lsString2 == "true"){
                StageData.bgMusicClose = true;
            }else if(lsString2 == "false"){
                StageData.bgMusicClose = false;
            }
         } catch(e) {
            alert("数据加载错误，请检查网络重新打开连接！");
         }
         //游戏
         this.getServerFinfo();
    }

    //加载服务器数据
    private getServerFinfo(){
       //从本地获取
       //var _token:string = egret.localStorage.getItem("token");//token 数据
       //var _areaCode:string = egret.localStorage.getItem("areaCode");//areaCode 数据

        var _token = MyUtils.getMyParamer("token")
        var _areaCode = MyUtils.getMyParamer("areaCode")

        if (!_token) {
            _token = Cookies.get('token')
        }
       
        if (!_areaCode) {
            //areaCode 数据
            _areaCode = Cookies.get('areaCode')
        }
       //alert("token："+_token);
       //alert("areaCode"+_areaCode);
       
       //取地址栏请求头
       var _HTTPTop:string = getJSUrl();
       if(_HTTPTop){
           StageData.requestHead = _HTTPTop.split(":")[0]; 
       }
       StageData.init();//刷新链接值
       //alert(StageData.linkStr);
       //alert(_token+":"+_areaCode+":"+MyUtils.getMyParamer("roundNo"));
       if(_token&&_areaCode){
           GameData.token = _token;//token 数据
           GameData.areaCode = _areaCode;//areaCode 数据       
           GameData.roundNo =  MyUtils.getMyParamer("roundNo");//回放           
           GameData.backurl = decodeURIComponent(MyUtils.getMyParamer("backurl"));//回放返回到上一个页面的地址
           //alert(decodeURIComponent(GameData.backurl));
           this.loaduserinfo();
          //获取用户信息
         }else{
           alert("点击了一个错误的分享链接，请退出！");
           return;
       }    
    }

    private loaduserinfo(){  
            var sdf:string = '{"source":{"gameId":11,"latitude":'+0+',"longitude":'+0+'},"type":1007,"token":"'+GameData.token+'"}';
            var post:PostLink = new PostLink();
            post.upload(StageData.HTTP_URL,new egret.URLVariables("?JSON="+sdf));
            post.once(post.UP_LOAD,this.userInfoComplete,this);
            post.once(post.LOAD_ERROR,(e)=>{
                alert(StringData.ERROR_code2.msg+StringData.ERROR_code2.code);
            },this);
   }
    private errorNum:number = 0;
    private loadUser_error(){
        //this.removeEventListener("loaderror",this.loadUser_error,this);
        if(this.errorNum < 2){    
            this.errorNum ++;
            this.loaduserinfo();
        }else{            
            alert(StringData.ERROR_code3.msg+StringData.ERROR_code3.code);
        }
    }

    private userInfoComplete(e){
        if(e.data&&e.data.errorCode == 0){
            if(e.data.source.roomConf){
                GameData.roomConf = e.data.source.roomConf;
                //alert("获取用户数据返回:"+JSON.stringify(e.data.source));
            }
            //获取战绩页面url
            if(e.data.source.combatPageAddr){
                StageData.recordLink = e.data.source.combatPageAddr;
            }
            StageData.serverAddress = e.data.source.gameServerAddr; 
            //alert(StageData.serverAddress);
            StageData.chatserverAddress = e.data.source.chatServerAddr; 
            StageData.gameHallLink = e.data.source.mainPageAddr;

             var userVo:any = e.data.source.succeedVo;//Json 用户数据
            // console.log(StageData.serverAddress+":"+StageData.chatserverAddress+" : "+userVo);
             if(!StageData.serverAddress||!StageData.chatserverAddress||!userVo){                 
                 alert(StringData.ERROR_code4.msg+StringData.ERROR_code4.code);
                 return;
             }
               // console.log("用户信息:"+userVo);
                GameData.reconnect = userVo.reconnect;//是否断线重连
                if(userVo.roomNo){
                    GameData.roomNo = String(userVo.roomNo);//房间号
                }
                var FXobj = new JSSDK();
                StageData.FXOBJ = FXobj;
                this.loadResource();
        }else{
            alert(e.data.message);//提示错误
        }
    }

    private loadResource(){
        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter",assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter",new ThemeAdapter());
        //Config loading process interface
        //设置加载进度界面
        // initialize the Resource loading library
        //初始化Resource资源加载库
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.loadConfig("resource/default.res.json?v=" + Math.random(), "resource/");
    }
    /**
     * 配置文件加载完成,开始预加载皮肤主题资源和preload资源组。
     * Loading of configuration file is complete, start to pre-load the theme configuration file and the preload resource group
     */
    private onConfigComplete(event:RES.ResourceEvent):void {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        // load skin theme configuration file, you can manually modify the file. And replace the default skin.
        //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
        let theme = new eui.Theme("resource/default.thm.json?v=" + Math.random(), this.stage);
        theme.addEventListener(eui.UIEvent.COMPLETE, this.onThemeLoadComplete, this);

        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);      
        RES.loadGroup("preload");
        // RES.loadGroup("pregame");
        onStageSize(this.onSize,this);
    }
    private isThemeLoadEnd: boolean = false;
    /**
     * 主题文件加载完成,开始预加载
     * Loading of theme configuration file is complete, start to pre-load the 
     */
    private onThemeLoadComplete(): void {
        this.isThemeLoadEnd = true;
        this.createScene();
    }
    private isResourceLoadEnd: boolean = false;
    /**
     * preload资源组加载完成
     * preload resource group is loaded
     */
    private onResourceLoadComplete(event:RES.ResourceEvent):void {
        if (event.groupName == "preload") {
            // this.removeChild(this.initTxt);
            this.loadingView.createView();
            RES.loadGroup("pregame");
        }
        if (event.groupName == "pregame") {
            this.isResourceLoadEnd = true;
            this.createScene();
        }
        if(event.groupName == "soundContent"){
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
            RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
                        
            this.loadBgMusic(StageData.bgMusicURL);
            this.setBgMusic();               
        }
    }
    //播放背景音乐
    private bgMusic:egret.Sound;
    private playposition:number = 0;
    private bgMsuicCh:egret.SoundChannel;
    public loadBgMusic(url:string){
         RES.getResByUrl(url,this.onBgMusicComplete,this,RES.ResourceItem.TYPE_SOUND);
    }
    private onBgMusicComplete(e){
        if(!this.bgMusic){
            this.bgMusic = e;
            // alert("music load complete");            
        }else{
            this.bgMsuicCh.stop();
            this.bgMusic = e;
        }
        
        if(this.bgMusic){
            this.bgMsuicCh = this.bgMusic.play(0,-1);
            this.setBgMusic();
        }

        /*if(GameData.roomInfo){
            var qxdStr:string = "";
                if(String(GameData.roomInfo.qiXiaoDuiWin) == "true"){
                    qxdStr = "；七小对可胡";
                }
                let shareUrl:string =StageData.linkStr+"/login/weiXin/"+GameData.areaCode+"?roomNo="+GameData.roomNo+"&type=10003";
                StageData.FXOBJ.setTitle("红中麻将 【房间号:"+GameData.roomNo+"】",GameData.zhifuStr[GameData.roomInfo.payType-1]+"；玩法："+GameData.ruleTypeStr[GameData.roomInfo.ruleType-1]+"；"+"局数："+GameData.roomInfo.totalTurns+qxdStr+"；房间已有"+GameData.roomInfo.userList.length+"人",shareUrl,"icon1");
        }*/ 
        //"红中麻将 【房间号:"+GameData.roomNo+"】",GameData.zhifuStr[msg.payType-1]+"；玩法："+GameData.ruleTypeStr[msg.ruleType-1]+"；"+"局数："+msg.totalTurns+qxdStr+"；房间已有"+msg.userList.length+"人",shareUrl,"icon1"
    }
    public playBgMusic(){
       if(this.bgMusic&&StageData.bgMusicClose){
           this.bgMsuicCh.volume = 1;
       }
    }
    public stopBgMusic(){        
        if(this.bgMusic){
          this.bgMsuicCh.volume = 0;
       }        
    }
    public JSSDKPlaySOUND(){
        if(this.bgMusic){
            this.bgMsuicCh = this.bgMusic.play(0,-1); 
            //this.setBgMusic();
        }        
    }
    //设置背景音乐是否播放
    public setBgMusic(){
       // console.log("背景音乐控制");
        if(StageData.bgMusicClose){
            this.playBgMusic();
        }else{
            this.stopBgMusic();
        }
    }
    private createScene(){
        if(this.isThemeLoadEnd && this.isResourceLoadEnd){
           this.startCreateScene();
        }
    }
    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onItemLoadError(event:RES.ResourceEvent):void {
        console.warn("Url:" + event.resItem.url + " has failed to load");
    }
    /**
     * 资源组加载出错
     * Resource group loading failed
     */
    private onResourceLoadError(event:RES.ResourceEvent):void {
        //TODO
        console.warn("Group:" + event.groupName + " has failed to load");
        //忽略加载失败的项目
        //ignore loading failed projects
        this.onResourceLoadComplete(event);
    }
    /**
     * preload资源组加载进度
     * loading process of preload resource
     */
    private onResourceProgress(event:RES.ResourceEvent):void {
        if (event.groupName == "pregame") {
            // this.initTxt.text = "请稍等..."+(Math.floor(event.itemsLoaded / event.itemsTotal * 100))+"%"; 
            this.loadingView.setProgress(event.itemsLoaded,event.itemsTotal);
        }
    }

    //接收聊天服务器消息
    public sockMessage(msg){
       // console.log("msg:"+msg);
        this.dispatchEventWith("sockMessage",false,msg);
    }
    //聊天服务器关闭
    public sockClose(){
        if(GameData.roundNo){//回放
            return;
        }
        //重新连接
        StageData.GameRoot.clew("聊天服务器已关闭");
        if(StageData.chatserverAddress){
            var lsTimer = egret.setTimeout(()=>{
                egret.clearTimeout(lsTimer);
                InitServerUrl(StageData.chatserverAddress);
            },this,1000);
        }
    }
    //聊天服务器已开启
    public sockOpen(){
        StageData.GameRoot.clew("聊天服务器已开启");
    }

    //回放
    public huifang_ok(e){
        StageData.MainObj.dispatchEventWith("playback_ok",false,e);
    }

    public huifang_error(){
        //回放数据报错
        StageData.MainObj.dispatchEventWith("playback_error");
    }
        
    /**
     * 创建场景界面
     * Create scene interface
     */
    
    protected startCreateScene(): void {
        // this.loadingView.clear();
        if(this.loadingView && this.loadingView.parent){
            this.loadingView.parent.removeChild(this.loadingView); 
        }    
        //添加游戏环境
        var gamestage:GameStage = new GameStage();
        this.addChild(gamestage);
        RES.loadGroup("soundContent");//加载声音资源
    }
}
